import { StyleSheet, Modal, View, Text, Pressable } from 'react-native';
import React, { useRef, useState, useEffect } from 'react';
import Recorder from 'react-native-audio-recorder-player';
import { useTranslation } from 'react-i18next';
import { uploadAudio } from '~/utils/upload';
import { px2dp, scale } from '~/utils/px2dp';
import { formatTime } from '~/utils/formatDate';
import { WaveformAnimation } from '~/components';
interface Props {
    visible: boolean;
    onCancel: Function;
    onConfrim: Function;
}
export default function UpoadAudioMode(props: Props) {
    const { visible, onCancel, onConfrim } = props;
    const recorder = useRef(new Recorder());
    const { t } = useTranslation();
    const [isPlaying, setIsPlaying] = useState(false);
    const [play, setPlay] = useState(true);
    const [audio, setAudio] = useState({ videoid: '', video_url: '' });
    const [stop, setStop] = useState(false);
    const [record, setRecord] = useState({
        recordSecs: 0,
        recordTime: '00:00',
    });

    // 开始录音
    const startRecording = async () => {
        if (stop) {
            Toast.show({ content: t('doctor.t34'), layout: 'top' });
            return;
        }
        setPlay(false);
        await recorder.current.startRecorder();
        recorder.current.addRecordBackListener((e) => {
            const time = formatTime(e.currentPosition);
            setRecord({
                recordSecs: e.currentPosition,
                recordTime: time,
            });
        });
        setIsPlaying(true);
    };
    // 停止录音
    const stopRecording = async () => {
        try {
            if (record.recordSecs < 1000) {
                Toast.show({ content: t('doctor.t35'), layout: 'top' });
                return;
            }
            setStop(true);
            // setIsPlaying(false);
            Toast.show({ content: t('doctor.t34'), layout: 'top' });
            audioUpload();
        } catch (error) {}
    };
    const audioUpload = async () => {
        setPlay(true);
        const result = await recorder.current.stopRecorder();
        const audioResult: any = await uploadAudio(result);
        if (audioResult.videoid) {
            Toast.show({ content: t('doctor.t36'), layout: 'top' });
        }
        setAudio(audioResult);
        setStop(false);
        setIsPlaying(false);
        recorder.current.removeRecordBackListener();
    };

    const submit = () => {
        let obj = {
            audio_id: audio?.videoid,
            audio_url: audio?.video_url,
            duration: record?.recordSecs,
        };
        onConfrim && onConfrim(obj);
        onCancel();
    };
    const cancel = () => {
        setPlay(true);
        setStop(false);
        setIsPlaying(false);
        setRecord({ recordSecs: 0, recordTime: '00:00' });
        setAudio({ videoid: '', video_url: '' });
        recorder.current.removeRecordBackListener();
        onCancel && onCancel();
    };
    useEffect(() => {
        if (record?.recordSecs >= 60000) {
            Toast.show({ content: t('doctor.t37'), layout: 'top' });
            audioUpload();
        }
    }, [record?.recordSecs]);
    return (
        <Modal
            visible={visible}
            animationType="fade"
            transparent={true}
            statusBarTranslucent={true}
            hardwareAccelerated={true}>
            <View style={styles.modal}>
                <View style={styles.modalContent}>
                    <View style={[styles.modal_header, styles.row]}>
                        <Pressable onPress={cancel}>
                            <Text style={styles.cancel}>{t('doctor.t38')}</Text>
                        </Pressable>
                        <Text style={styles.title}>{t('doctor.t39')}</Text>
                        <View />
                    </View>
                    <Text style={styles.tips}>{t('doctor.t40')}</Text>
                    <View style={styles.bottom}>
                        <Text style={styles.recordTime}>{record.recordTime}</Text>
                        <View style={styles.wave}>
                            <WaveformAnimation isPlaying={isPlaying} />
                        </View>
                        {audio?.videoid ? (
                            <Pressable style={styles.bootom_button} onPress={submit}>
                                <Text style={styles.bootom_buttonText}>{t('doctor.t41')}</Text>
                            </Pressable>
                        ) : (
                            <Pressable
                                style={styles.bootom_button}
                                onPress={() => {
                                    if (!isPlaying) {
                                        startRecording();
                                    } else {
                                        stopRecording();
                                    }
                                }}>
                                <Text style={styles.bootom_buttonText}>
                                    {!isPlaying ? t('doctor.t42') : t('doctor.t43')}
                                </Text>
                            </Pressable>
                        )}
                    </View>
                </View>
            </View>
        </Modal>
    );
}

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },
    modal: {
        flex: 1,
        backgroundColor: 'rgba(0,0,0,0.2)',
        justifyContent: 'flex-end',
    },
    modalContent: {
        backgroundColor: '#fff',
        height: '50%',
        padding: px2dp(32),
        width: '100%',
        borderTopLeftRadius: 24,
        borderTopRightRadius: 24,
    },
    title: {
        fontSize: scale(30),
        fontWeight: 'bold',
        textAlign: 'center',
        color: '#191919',
    },
    tips: {
        color: '#a4a4a4',
        fontSize: scale(26),
        marginTop: px2dp(30),
    },
    bottom: {
        justifyContent: 'flex-end',
        flexGrow: 1,
    },
    bootom_button: {
        backgroundColor: '#1877FF',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: px2dp(16),
        height: px2dp(100),
        marginTop: '10%',
    },
    bootom_buttonText: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
    recordTime: {
        textAlign: 'center',
    },
    modal_header: {
        justifyContent: 'space-between',
    },
    cancel: {
        fontSize: scale(30),
        color: '#a4a4a4',
    },
    wave: {
        width: '80%',
        alignSelf: 'center',
        marginTop: px2dp(64),
    },
});
